﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using WebCommit.Common.Helpers;
using NHibernate;
using WebCommit.Common.Entitys;
using System.Web.Caching;

namespace WebCommit.Common.Constants
{
	public static class Resource
	{
		//private static object LockObj = new object();
		//static Resource()
		//{
		//    lock (LockObj)
		//    {
		//        AddCache();
		//    }
		//}

		//private static void CacheExpireCallBack(string key, object obj, System.Web.Caching.CacheItemRemovedReason removeReason)
		//{
		//    if (key == "ResourceTable")
		//    {
		//        AddCache();
		//    }
		//}

		//private static void AddCache()
		//{
		//    System.Web.Caching.Cache cache = System.Web.HttpRuntime.Cache;
			
		//    if (GetCache() == null)
		//        cache.Add("ResourceTable", GetResource(), null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, Utility.GetAppCfg<int>(Config.ResourceCacheExpireTimeSpan), 0), System.Web.Caching.CacheItemPriority.Default, new System.Web.Caching.CacheItemRemovedCallback(CacheExpireCallBack));
		//}

		//private static Hashtable GetResource()
		//{
		//    ISession sess = NHibernateHelper.GetSession(Config.HBSessionKey_WebCommit);
		//    IList<ResourceEntity> list = sess.CreateCriteria<ResourceEntity>().List<ResourceEntity>();
		//    Hashtable table = new Hashtable();
		//    foreach (ResourceEntity item in list)
		//    {
		//        table.Add(item.Key, item.Value);
		//    }
		//    return table;
		//}

		//private static Hashtable GetCache()
		//{

		//    System.Web.Caching.Cache cache = System.Web.HttpRuntime.Cache;
		//    if (System.Web.HttpContext.Current.Cache.Get("ResourceTable") == null)
		//    {
		//        return null;
		//    }
		//    else
		//        return cache.Get("ResourceTable") as Hashtable;
			
		//}

		public static T GetResource<T>(string key)
		{
			//object v = GetCache()[key];
			ISession sess = NHibernateHelper.GetSession(Config.HBSessionKey_WebCommit);
			IList<ResourceEntity> list = sess.CreateCriteria<ResourceEntity>().List<ResourceEntity>();
			ResourceEntity res = list.First(o => o.Key == key);
			object v = res.Value;
			Type t = typeof(T);
			return (T)Convert.ChangeType(v, typeof(T));
		}
		public static string GetResource(string key)
		{
			return GetResource<string>(key);
		}
	}
}
